package com.zjuh.goodboy.filter.filters;

import java.util.ArrayList;
import java.util.List;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import com.zjuh.goodboy.awires.AppContextAwire;
import com.zjuh.goodboy.claw.link.Link;
import com.zjuh.goodboy.context.AppContext;
import com.zjuh.goodboy.filter.FilterContext;
import com.zjuh.goodboy.store.link.LinkManager;
import com.zjuh.goodboy.util.JsoupUtil;
import com.zjuh.goodboy.util.StringUtil;
import com.zjuh.goodboy.util.URLUtil;

public class LinkExportParserFilter extends BaseFilter implements AppContextAwire {

	private AppContext appContext;
	
	@Override
	public void setAppContext(AppContext appContext) {
		this.appContext = appContext;
	}

	@Override
	public void onFilter(Link link, String input, FilterContext filterContext) {
		Document doc = Jsoup.parse(input);
		Elements elements = doc.getElementsByTag("a");

		LinkManager linkManager = (LinkManager)appContext.getObject("linkManager");
		
		final String path = URLUtil.getBase(link.getUrl());
		List<Link> links = new ArrayList<Link>();
		for (Element element : elements) {
			String href = element.attr("href");
			if (StringUtil.isEmpty(href)) {
				continue;
			}
			String text = JsoupUtil.getLinkText(element);
			if (log.isDebugEnabled()) {
				log.debug("base url " + path);
			}
			String targetUrl = URLUtil.makeUrl(path, href);
			Link newLink = new Link(targetUrl, text);
			
			if (log.isDebugEnabled()) {
				log.debug("parsed link: " + newLink);
			}
			links.add(newLink);
		}
		try {
			linkManager.saveLinks(links);
		} catch (Exception e) {
			log.error("onFilter error", e);
		}
	}
	
}
